﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace MyTRCP.Common.Services
{
    public class AudioAvgLouldnessComputeService : BackgroundService
    {
        private readonly ILogger<AudioAvgLouldnessComputeService> _logger;
        private readonly BlockingQueue<byte[]> _pcmQueue;
        public event EventHandler<short>? LouldnessChanged;
        private short _lastLn;
        public AudioAvgLouldnessComputeService(ILogger<AudioAvgLouldnessComputeService> logger)
        {
            logger.LogDebug($"AudioAvgLouldnessComputeService creating...");
            _logger = logger;
            _pcmQueue = new BlockingQueue<byte[]>();
            _lastLn = 0;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            await Task.Run(() => ThreadMethod(stoppingToken), stoppingToken);
        }
        public override Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogDebug("startasync called");
            return base.StartAsync(cancellationToken);
        }
        public override Task StopAsync(CancellationToken cancellationToken)
        {
            _pcmQueue.CancelTake();
            return base.StopAsync(cancellationToken);
        }
        public BlockingQueue<byte[]> PcmQueue
        {
            get
            {
                return _pcmQueue;
            }
        }
        private void ThreadMethod(CancellationToken stoppingToken)
        {
            try
            {
                while (!stoppingToken.IsCancellationRequested)
                {
                    try
                    {
                        UpdateLouldness(_pcmQueue.Take());
                    }
                    catch (OperationCanceledException)
                    {
                        _logger.LogInformation("语音响度计算线程收到取消信号，退出");
                        break;
                    }
                    catch (Exception e)
                    {
                        _logger.LogError(e, $"语音响度计算线程循环内出现异常：{e.Message}");
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"语音响度计算线程异常：{ex.Message}");
            }
        }

        private void UpdateLouldness(byte[] data)
        {
            if (data.Length == 1)
                return;
            ulong sum = 0;
            short single = 0;
            short avg = 0;
            if (data.Length > 0)
            {
                for (int i = 0; i < data.Length; i++)
                {
                    if (i % 2 == 0)
                    {
                        single = data[i];
                    }
                    else
                    {
                        single |= (short)(data[i] << 8);
                        if (single < 0)
                            single = (short)-single;
                        sum += (ulong)single;
                    }
                }
                avg = (short)(sum * 2 / (ulong)data.Length);
            }
            if (avg != _lastLn)
            {
                _lastLn = avg;
                LouldnessChanged?.Invoke(this, _lastLn);
            }
        }
    }
}
